<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


class UsersController extends AppController {

    var $layout = 'default';
    var $name = 'Users';
    var $uses = array(
        'User'
    );
    var $helpers = array('Cache');
    var $cacheAction = array(
        'login' => 120,
    );
    var $yahoo_auth = null;
    var $facebook_auth = null;

    function logout() {
        $this->Auth->logout();
        $this->redirect('/trang-chu.html');
    }
    /*
    function login() {

        $this->set('title_for_layout', 'www.thegioigamevui.com .:. Đăng nhập');

        if (!$this->Auth->user()) {
            if ($this->data) {
                if ($this->Auth->identify($this->data)) {
                    $this->Session->setFlash('Chúc mừng bạn đã đăng nhập thành công', 'msg', array(), 'msg');
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                } else {

                    $this->Session->setFlash('Username hoặc password không đúng hoặc bạn chưa kích hoạt tài khoản', 'error', array(), 'msg');
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                }
            }
        } else {
            $this->redirect(array('controller' => 'default', 'action' => 'index'));
        }
    }
    */
    function login_yahoo() {
        App::import('Vendor', 'yahoo');
        $this->yahoo_auth = YahooSession::hasSession(Configure::read('yahoo_key'), Configure::read('yahoo_secret'), Configure::read('yahoo_appid'));
        $auth_url = YahooSession::createAuthorizationUrl(Configure::read('yahoo_key'), Configure::read('yahoo_secret'), YahooUtil::current_url() . "?in_popup");
        if (!$this->yahoo_auth) {
            $this->redirect($auth_url);
        } else {
            $session = YahooSession::requireSession(Configure::read('yahoo_key'), Configure::read('yahoo_secret'), Configure::read('yahoo_appid'));
            $user = $session->getSessionedUser();
            // Load the profile for the current user.
            $profile = $user->getProfile();
            $user_exist_check = $this->User->find('first', array(
                        'conditions' => array(
                            'User.username' => $profile->guid,
                            'User.service' => 'yahoo'
                        )
                    ));
            $data = array();
            $email = '';
            if (is_array($profile->emails)) {
                foreach ($profile->emails AS $row) {
                    if ($row->primary) {
                        $email = $row->handle;
                        break;
                    }
                }
            }
            $data = array(
                'username' => $profile->guid,
                'fullname' => $profile->nickname,
                'service' => 'yahoo',
                'email' => $email,
                'openid' => '1',
                'birthday' => "{$profile->birthdate}/{$profile->birthYear}",
                'avatar' => "/img/no_avatar.gif",
                'location' => $profile->location,
            );
            if ($profile->gender == 'M') {
                $data['sex'] = '1';
            } else {
                $data['sex'] = '0';
            }

            if ($user_exist_check) {
                $data['id'] = $user_exist_check['User']['id'];
                $this->User->save($data);
            } else {
                $this->User->save($data);
                $data['id'] = $this->User->lastInsertId();
            }
            //unset($data['id']);
            $this->Session->write($this->Auth->sessionKey, $data);
            YahooSession::clearSession();
            echo '<script type="text/javascript">window.opener.location.reload(true);window.close();</script>';
        }
        exit;
    }

    function login_facebook() {
        App::import('Vendor', 'facebook/facebook');
        $this->facebook_auth = new Facebook(array(
                    'appId' => Configure::read('facebook_appid'),
                    'secret' => Configure::read('facebook_secret'),
                    'fileUpload'    =>  true
                ));
        $params = array(
            'scope' => 'email,user_birthday,publish_actions,status_update,publish_stream',
            'redirect_uri' => Configure::read('baseUrl') . '/users/login_facebook/'
        );
        $auth_url = $this->facebook_auth->getLoginUrl($params);
        $profile    =   false;
        
        if (!$this->facebook_auth->getUser()) {
            $this->redirect($auth_url);
        } else {
            $profile = $this->facebook_auth->api('/me');
            
            // Load the profile for the current user.
            $user_exist_check = $this->User->find('first', array(
                        'conditions' => array(
                            'User.username' => $profile['id'],
                            'User.service' => 'facebook'
                        )
                    ));


            $data = array(
                'username' => $profile['id'],
                'fullname' => $profile['name'],
                'first_name' => $profile['first_name'],
                'last_name' => $profile['last_name'],
                'email' => $profile['email'],
                'service' => 'facebook',
                'openid' => '1',
                'birthday' => $profile['birthday'],
                'avatar' => "/img/no_avatar.gif",
                'location' => $profile['location']['name']
            );
            if ($profile['gender'] == 'male') {
                $data['sex'] = '1';
            } else {
                $data['sex'] = '0';
            }
            if ($user_exist_check) {
                $data['id'] = $user_exist_check['User']['id'];
                $this->User->save($data);
            } else {
                $this->User->save($data);
                $data['id'] = $this->User->lastInsertId();

                $post_photo = $this->facebook_auth->api('/me/photos', 'POST', array(
                            'Source' => '@' . Configure::read('avatar_website'),
                            'message' => 'Bạn ' . $profile['name'] . ' Thân mến! cám ơn bạn đã ủng hộ Thế Giới Game Vui, mong bạn tiếp tục ghé thăm và ủng hộ khi có thời gian nhé! -- http://thegioigamevui.com --',
                        ));
            }
            //unset($data['id']);
            $this->Session->write($this->Auth->sessionKey, $data);
            $this->facebook_auth->destroySession();
            echo '<script type="text/javascript">window.opener.location.reload(true);window.close();</script>';
        }
        exit;
    }

    function login_gmail() {
        App::import('Vendor', 'google/auth_handler');
        App::import('Vendor', 'google/config');

        $client = new apiClient();
        $client->setClientId(Configure::read('google_client_id'));
        $client->setClientSecret(Configure::read('google_client_secret'));
        $client->setRedirectUri(Configure::read('baseUrl') . '/users/login_gmail');
        $client->setUseObjects(true);
        try {
        $userInfoService = new apiOauth2Service($client);
         } catch (Exception $e) {
            print_r($e);exit;
        }
        $gmail_logined = false;
        try {
            if($client->authenticate()){
                $gmail_logined  =true;
            }
            
        } catch (Exception $e) {
        }
        if ($gmail_logined) {
            $user = $userInfoService->userinfo->get();
            $user_exist_check = $this->User->find('first', array(
                        'conditions' => array(
                            'User.username' => $user->id,
                            'User.service' => 'google'
                        )
                    ));
            $data = array(
                'username' => $user->id,
                'fullname' => $user->name,
                'email' => $user->email,
                'service' => 'google',
                'openid' => '1',
                'birthday' => $user->birthday,
                'avatar' => "/img/no_avatar.gif",
                'location' => $user->locale
            );
            if ($user->gender == 'male') {
                $data['sex'] = '1';
            } else {
                $data['sex'] = '0';
            }
            if ($user_exist_check) {
                $data['id'] = $user_exist_check['User']['id'];
                $this->User->save($data);
            } else {
                $this->User->save($data);
                $data['id'] = $this->User->lastInsertId();
            }
            //unset($data['id']);
            $this->Session->write($this->Auth->sessionKey, $data);
            $client->revokeToken();
            echo '<script type="text/javascript">window.opener.location.reload(true);window.close();</script>';
        }
        exit;
    }

}

?>
